<?php
namespace app\api\controller;

use app\common\controller\Response;
use app\common\controller\Token;
use app\api\model\Permissions as PerModel;

use think\Request;
use think\Db;

class Login extends Response
{
    public function index(Request $request)
    {
        if (Request::instance()->isPost()) {
            $account = $request->post('userName', null);
            $password = $request->post('password', null);
            if (empty($account)) {
                $this->responseJson(1003);
            }
            if (empty($password)) {
                $this->responseJson(1004);
            }
            $user = Db::name('admin')->where(['account'=>$account])->field('id, password, status, salt, nickname, type, img')->find();
            if (empty($user)){
                $this->responseJson(1005);
            }
            if (md5($password.$user['salt'].'$%$^%$&^%&') !== $user['password']){
                $this->responseJson(1006);
            }
            if($user['status'] === 0){
                $this->responseJson(1007);
            }
            $tmp = new Token();
            // 获取该账号下的权限、
            $permissions = $this->obtain($account);
            $data = [
                'token'       => $tmp->setToken($account),// token
                'type'        => $user['type'],// 属于那个类型
                'id'          => $user['id'],
                'nickname'    => $user['nickname'],
                'permissions' => $permissions,// 权限
                'time'        => time(),
            ];
            $this->responseJson(1000, $data);
        }
        $this->responseJson(1002);
    }

    //获取该管理员权限
    public function obtain($account)
    {
        //获取该用户角色
        $rid = Db::name('admin')->where('account', $account)->field('type')->find();
        //判断角色是否存在
        $tmp = Db::name('roles')->where('id', $rid['type'])->find();
        if (empty($tmp)){
            return false;
        }
        //获取该角色下的权限
        $permissions = Db::name('rolepermissions')->where('role_id', $tmp['id'])->find();
        if(empty($permissions)){
            return [];
        }
        $data = json_decode($permissions['permission_id'], true);
        $data = PerModel::all($data);
        if (empty($data)){
            return [];
        }
        foreach ($data as $key=>$val){
            $list[$key]['id']         = $val['id'];
            $list[$key]['title']      = $val['title'];
            $list[$key]['controller'] = $val['controller'];
        }
        return  $list;
    }
}
